package exception

import (
	"fmt"
)

type ReadExceptionCode string

type ReadException interface {
	error
	IsException() bool
}

var (
	READ_LENGTH_SHORT    ReadExceptionCode = "30001" //读取时，未读到5位长度
	PREFIX_LENGTH_VERIFY ReadExceptionCode = "30002" //读取时，长度验证失败
	READ_DATA_FAILED     ReadExceptionCode = "30003" //读取时，读取数据失败
	DATA_LENGTH_VERIFY   ReadExceptionCode = "30004" //读取时，读取数据完成后长度验证不通过
	DATA_LENGTH_LIMIT    ReadExceptionCode = "30005" //读取时，读取数据完成后长度验证不通过

	DECODE_FAILED ReadExceptionCode = "40001" //解密失败
	ENCODE_FAILED ReadExceptionCode = "40002" //加密失败
)

var errCodeName = map[ReadExceptionCode]string{
	READ_LENGTH_SHORT:    "read length < 5",
	PREFIX_LENGTH_VERIFY: "read length verify failed",
	READ_DATA_FAILED:     "read data failed",
	DATA_LENGTH_VERIFY:   "read data length not equals analyze length",
	DATA_LENGTH_LIMIT:    "read data length out limit",

	DECODE_FAILED: "decode failed",
	ENCODE_FAILED: "encode failed",
}

func (e ReadExceptionCode) String() string {
	if s, ok := errCodeName[e]; ok {
		return s
	}
	return fmt.Sprintf("unknown exception code %s", string(e))
}

type ReadExceptionInfo struct {
	ErrCode ReadExceptionCode
	ErrMsg  string
}

func NewException(code ReadExceptionCode) error {
	globalReadExceptionInfo := ReadExceptionInfo{
		ErrCode: code,
		ErrMsg:  code.String(),
	}

	return globalReadExceptionInfo
}
func NewExceptionByError(code ReadExceptionCode, err error) error {
	globalReadExceptionInfo := ReadExceptionInfo{
		ErrCode: code,
		ErrMsg:  fmt.Sprintf("%s: %s", code.String(), err.Error()),
	}

	return globalReadExceptionInfo
}

func (e ReadExceptionInfo) Error() string {
	if e.ErrMsg == "" {
		return e.ErrCode.String()
	}
	return e.ErrMsg
}

func (e ReadExceptionInfo) IsException() bool {
	return true
}

func (e ReadExceptionInfo) Code() ReadExceptionCode {
	return e.ErrCode
}

func ExceptionToStatusCode(err interface{}, code ReadExceptionCode, msg string) (status string, errMsg string) {
	_, ok := err.(ReadExceptionInfo)
	if ok {
		if msg == "" {
			return string(err.(ReadExceptionInfo).Code()), err.(ReadExceptionInfo).Error()
		} else {
			return string(err.(ReadExceptionInfo).Code()), msg
		}
	} else {
		if msg == "" {
			if code == "" {
				return string(code), err.(error).Error()
			} else {
				return string(code), code.String()
			}
		} else {
			return string(code), msg
		}
	}
}

func ExceptionEqual(err interface{}, code ReadExceptionCode) bool {
	XErr, ok := err.(ReadExceptionInfo)
	if ok {
		return XErr.Code() == code
	}
	return false
}
